package com.whmall.service.crm.util;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.*;

/**
 * 作者：lizw <br/>
 * 创建时间：2021/11/02 18:49 <br/>
 */
public class BeanCopyUtils {
//    public static void copyProperties(Object source, Object target, boolean ignoreSourceNull, boolean ignoreTargetNull) {
//        List<String> ignoreProperties = new ArrayList<>();
//        if (ignoreSourceNull) {
//            ignoreProperties.addAll(Arrays.asList(getNullPropertyNames(source)));
//        }
//        if (ignoreTargetNull) {
//            ignoreProperties.addAll(Arrays.asList(getNullPropertyNames(target)));
//        }
//        BeanUtils.copyProperties(source, ignoreProperties.toArray(new String[]{}));
//    }
//
//    public static void copyIgnoreNull(Object source, Object target) {
//        copyProperties(source, target, true, true);
//    }
//
//
//    public static void copyIgnoreSourceNull(Object source, Object target) {
//        copyProperties(source, target, true, false);
//    }
//
//    public static void copyIgnoreTargetNull(Object source, Object target) {
//        copyProperties(source, target, false, true);
//    }

    public static void copySrcNotNullAndTargetNull(Object source, Object target) {
        List<String> ignoreProperties = new ArrayList<>();
        ignoreProperties.addAll(Arrays.asList(getNullPropertyNames(source)));
        ignoreProperties.addAll(Arrays.asList(getNotNullPropertyNames(target)));
        BeanUtils.copyProperties(source, target, ignoreProperties.toArray(new String[]{}));
    }

    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    private static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    private static String[] getNotNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue != null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
